package com.yizhang.config;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: yi.zhang
 * @CreateTime: 2025-09-25 17:36:26
 * @Description:
 */
@Configuration
public class RocketMQConfig {

    @Value("${rocketmq.name-server}")
    private String nameServer;

    @Value("${rocketmq.producer.group}")
    private String producerGroup;

    @Value("${rocketmq.producer.send-message-timeout}")
    private int sendMessageTimeout;

    @Value("${rocketmq.producer.retry-times-when-send-failed}")
    private int retryTimesWhenSendFailed;


    /**
     * 配置 DefaultMQProducer（RocketMQ 底层生产者）
     */
    @Bean
    public DefaultMQProducer defaultMQProducer() {
        DefaultMQProducer producer = new DefaultMQProducer(producerGroup);
        // 设置 NameServer 地址
        producer.setNamesrvAddr(nameServer);
        // 自定义参数（可选）
        producer.setSendMsgTimeout(sendMessageTimeout);
        producer.setRetryTimesWhenSendFailed(retryTimesWhenSendFailed);
        return producer;
    }


    /**
     * 配置 RocketMQTemplate（Spring 封装的模板类，依赖上面的 DefaultMQProducer）
     */
    @Bean
    public RocketMQTemplate rocketMQTemplate(DefaultMQProducer defaultMQProducer) {
        RocketMQTemplate template = new RocketMQTemplate();
        // 绑定底层生产者
        template.setProducer(defaultMQProducer);
        return template;
    }
}
